import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import { message } from 'antd'
import { convertContent } from '../constant/lang-util'

export const getSurveyQuizzes = (page = 1, pageSize = 10, searchConditions = {}) => {
  const {id, userId, description, tags = []} = searchConditions
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/surveyQuizzes/pageable?page=${--page}&pageSize=${pageSize}
      ${id ? '&quizId=' + id : ''}
      ${userId ? '&userId=' + userId : ''}
      ${description ? '&description=' + description : ''}
      ${tags.length ? '&tags=' + tags : ''}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'GET_SURVEY_QUIZZES_PAGEABLE',
          data: res.body
        })
      }
    })()
  }
}

export const addSurveyQuiz = (quiz,) => {
  return () => {
    (async () => {
      const res = await request.post(`./api/surveyQuizzes`, quiz)
      if (res.status === HTTP_CODE.CREATED) {
        message.success(convertContent('添加成功'))
      }
    })()
  }
}

export const getSurveyQuiz = (quizId) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/surveyQuizzes/${quizId}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: 'GET_SURVEY_QUIZ',
          data: res.body
        })
      }
    })()
  }
}

export const editSurveyQuiz = (quiz) => {
  return () => {
    (async () => {
      const res = await request.update(`./api/surveyQuizzes/${quiz.id}`,quiz)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success(convertContent('修改成功'))
      }
    })()
  }
}

export const deleteQuiz = (quizId) => {
  return dispatch => {
    (async () => {
      const res = await request.del(`./api/surveyQuizzes/${quizId}`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success(convertContent('删除成功'))
        dispatch(getSurveyQuizzes())
      }
    })()
  }
}
